package com.mysteel.rabbitmq.topic.producer;

import com.alibaba.fastjson.JSON;
import com.mysteel.rabbitmq.LoadMessage;
import com.mysteel.rabbitmq.MqConfig;
import com.mysteel.rabbitmq.topic.TopicUtil;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.UUID;

/**
 *  Topic demo
 *    发送消息只需要制定
 *    EXCHANGE & ROUTING
 * @author tannc
 */
public class ProducerApplication {



    public static void main(String[] args) throws Exception {

        // 创建连接和频道
        Channel channel = TopicUtil.createChannel();
        // 声明转发器
        channel.exchangeDeclare(TopicUtil.EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        //定义绑定键
        String[] routing_keys = TopicUtil.ROUTING_KEYS;
        LoadMessage loadMessage;
        Random random = new Random();
        String content = "";
        while (true) {
            for (String routing_key : routing_keys) {
                //发送4条不同绑定键的消息
                loadMessage = LoadMessage.builder()
                        .timstamp(System.currentTimeMillis())
                        .uuid(UUID.randomUUID().toString())
                        .data(random.nextInt(10000000)).build();
                content = JSON.toJSONString(loadMessage);
                // 发送数据
                System.out.println(String.format(" routing_key：%s =>  send message :%s", routing_key, content));
                channel.basicPublish(TopicUtil.EXCHANGE_NAME, routing_key, MessageProperties.TEXT_PLAIN, content.getBytes(StandardCharsets.UTF_8));
            }
            // 每10秒
            Thread.sleep(10000);
        }

    }
}
